package com.ruoyi.api.controller;

import com.ruoyi.api.service.InterceptUtilService;
import com.ruoyi.api.service.InventoryService;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.service.AICodeService;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.service.WarehousingService;
import org.slf4j.impl.StaticLoggerBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.ruoyi.common.core.domain.AjaxResult.Type.OTHER;

/**
 * @author PDA 销货单
 */
@RestController
@RequestMapping("/api/business/salegoods")
public class SelectSaleGoodsController extends BaseController {

    @Autowired
    ISaleGoodsService saleGoodsService;
    @Autowired
    ISaleorderService saleorderService;
    @Autowired
    AuditService auditService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    AICodeService aiCodeService;
    @Autowired
    ProductServer productServer;
    @Autowired
    InterceptUtilService interceptUtilService;
    @Autowired
    WarehousingService warehousingService;
    @Autowired
    ISysUserService userService;
    @Autowired
    ICompanyInvoiceService invoiceService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private ISaleorderService iSaleorderService;

    @Autowired
    private SaleGoodsMapper saleGoodsMapper;


    @Autowired
    private ProcurementServer procurementServer;

    @PostMapping("/goodsList")
    @ResponseBody
    public TableDataInfo getlist(SaleGoodsOrder saleGoodsOrder) {

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        startPage();
        saleGoodsOrder.setDeptId(sysUser.getCompanyId());
//        saleGoodsOrder.setDeptId(101L);
        saleGoodsOrder.setSaleGoodsStatus("-1");
//        saleGoodsOrder.setDeptName((saleGoodsOrder.getDeptName() == null || saleGoodsOrder.getDeptName().equals("")) ? null : saleGoodsOrder.getDeptName());
//        saleGoodsOrder.setIsWarehousingOrder(-1);
        List<SaleGoodsOrder> list = saleGoodsService.selectSaleGoodsListByPDA(saleGoodsOrder);
//        List<SaleGoodsOrder> list = saleGoodsService.selectSaleGoodsList(saleGoodsOrder);
        String loggerFactoryClassStr = StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr();
        logger.error(loggerFactoryClassStr);
        return getDataTable(list);
    }

    /**
     * 重写分页数据
     *
     * @param msg  提示信息
     * @param list 数据
     * @return 结果
     */
    protected TableDataInfo getDataTable2(String msg, List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(list.size());
        return rspData;
    }

    /**
     * 根据companyId 查询 公司名称
     */
    @PostMapping("/addSale")
    @ResponseBody
    public AjaxResult addSale() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long companyId = sysUser.getCompanyId();
//        Long companyId = 101L;
        Map<String, Object> map = new HashMap<>();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        String format = "";
        Date dates = null;
        try {
//            String format = a.format(new Date());
            format = a.format(new Date());
            map.put("dates", format);
//            Date dates = a.parse(format);

            map.put("saleorderDate", format);
            dates = a.parse(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //生成的订单编号
        String s = purchaseOrderService.orderNum(dates, 2);
        if (s.equals("0")) {
            return AjaxResult.error("请先设置前缀");
        }
        map.put("saleorderNum", s);
        return AjaxResult.success(map);
    }

    /**
     * 根据companyId 查询 公司名称
     */
    @PostMapping("/selectDeptNameById")
    @ResponseBody
    public AjaxResult selectDeptNameById() {
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//        Long companyId = 101L;
        Map<String, Object> map = new HashMap<>();
        map.put("user", userService.selectSalesmanList(companyId));
        return AjaxResult.success(map);
    }

    /**
     * 查询销售订单信息
     *
     * @param saleorderOrder 查询条件
     * @return 结果
     */
    @PostMapping("/saleList")
    @ResponseBody
    public TableDataInfo getSalelist(SaleorderOrder saleorderOrder) {

        startPage();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//        Long companyId = 101L;
        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setIsCreateGoods("0");
        List<Long> longs1 = saleorderService.selectById(companyId);
        List<SaleorderOrder> saleGoodsOrder = new ArrayList<>();
        if (longs1.size() != 0) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("deptId", companyId);
            hashMap.put("saleGoodsId", longs1);
            saleGoodsOrder = saleorderService.selectSaleGoodsByMap(hashMap);
        }
        return getDataTable(saleGoodsOrder);
    }

    /**
     * 截取扫描的型号唯一码
     */
    @PostMapping("/interceptStr")
    @ResponseBody
    @Transactional
    public AjaxResult interceptStr(String[] barCode, String modelCode) {

        for (int i = 0; i < barCode.length; i++) {
            barCode[i] = barCode[i].replaceAll("\\(|\\)", "");

        }
        //调用截取字符串判断是否与传入的唯一码是否一致
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//        Long companyId = 101L;
        String intercept = interceptUtilService.intercept(barCode);
        if (intercept.equals("0") || intercept.equals("")) {
            return new AjaxResult(OTHER, "AI码扫描失败，请重新扫描");
        }
        if (modelCode == null || modelCode == "") {
            modelCode = intercept;
        } else {
            if (!modelCode.equals(intercept)) {
                return new AjaxResult(OTHER, "产品规格的型号唯一码不符，请扫描同一款的产品");
            }
        }
        //查询产品规格信息
        ProductModel productModel = productServer.selectProductByModelCode(companyId, modelCode);

        //定义新的库存变量
        List<Warehousing> warehousings = new ArrayList<>();
        if (productModel != null) {
            if (intercept.equals(productModel.getModelCode())) {
                Long productId = productModel.getProductId();
                String productType = productModel.getProductType();
                //定义存储截取后的字符串
                List<Map<String, String>> intercept1 = null;
                try {
                    intercept1 = interceptUtilService.intercept(productId, barCode, companyId, null);
                } catch (Exception e) {
//                    return new AjaxResult(OTHER, "" + e.getMessage() + "");
                    return new AjaxResult(OTHER, e.getMessage());
                }
                Warehousing warehousing = new Warehousing();
                if (intercept1.size() != 0) {
                    //定义变量，用于判断是否截取全部的字符串
                    int i = 0;
                    for (Map<String, String> map : intercept1) {
                        if (map.get("10") != null && map.get("17") != null) {
                            i++;
                            //产品批次
                            String s = map.get("10");
                            //产品的失效日期
                            String effectiveDate = map.get("17");
                            //产品的生产日期
                            String productDate = map.get("11");
                            warehousing.setProductId(productId);
                            warehousing.setSelectId(productId);
                            warehousing.setProductName(productModel.getProductName());
                            warehousing.setDeptId(companyId);
                            warehousing.setBatch(s);
                            warehousing.setModelCode(modelCode);
                            warehousing.setModelNo(productModel.getModelNo());
                            warehousing.setProductType(productType);
                            //查询产品库存信息
                            Warehousing warehousing1 = warehousingService.selectWarehousing(warehousing);
                            warehousing1.setFactor(productModel.getFactor());

                            //查询产品的生产时间，截取到则直接放入map中，否，则通过查询产品的生产日期计算规则生成生产日期
                            Date effectiveDates = SelectProcurementController.generateDate(effectiveDate);
                            Date productDates = null;
                            Map maps = new HashMap<String, Object>();
                            if (productDate == null || ("").equals(productId)) {
                                //计算添加生产时间
                                productDate = productServer.calculateDate(effectiveDate, productId);
                            }
                            //生产日期  时间类型转换，将string转换为date
                            productDates = SelectProcurementController.generateDate(productDate);
                            maps.put("productionDate", productDates);
                            maps.put("productId", productId);
                            maps.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
//                            maps.put("deptId", 101L);
                            //判断是否拥有产品库存，有则放入对象中
                            if (warehousing1 != null) {
                                //设置 产品医疗器械注册证编号 产品注册的失效日期
                                warehousing1.setProductionDate(productDates);
                                warehousing1.setEffectiveDate(effectiveDates);
                                warehousing1.setModelCode(modelCode);
                                warehousings.add(warehousing1);
                            }
                        }
                    }
                    if (warehousings.size() != 0) {
                        return AjaxResult.success("扫描成功", warehousings);
                    } else {
                        if (i == 0) {
                            return new AjaxResult(AjaxResult.Type.SPLICE, "扫描不全请重新扫描");
                        } else {
                            return new AjaxResult(OTHER, "扫描错误，请重新确认条形码信息");
                        }
                    }
                } else {
                    return new AjaxResult(OTHER, "该产品型号未找到，请重新确认条形码信息");
                }
            } else {
                return new AjaxResult(OTHER, "产品规格的型号唯一码不符，请重新确认条形码信息");
            }
        } else {
            return new AjaxResult(OTHER, "该产品型号未找到");
        }
    }

    /**
     * 新增保存销货单
     */
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult add(@RequestBody SaleGoodsOrder saleGoodsOrder) {

        String orderid = getStr();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        saleGoodsOrder.setOrderId(orderid);
//        return AjaxResult.error("这是错误测试");
        saleGoodsOrder.setSaleGoodsStatus("1");
        saleGoodsOrder.setCreateBy(sysUser.getNickName());
        saleGoodsOrder.setDeptId(sysUser.getCompanyId());
        //状态 0 申请中
        saleGoodsOrder.setSaleGoodsStatus("0");

        int insertOrderNum = saleGoodsMapper.insertSaleGoodsOrderPda(saleGoodsOrder);

        if (saleGoodsOrder.getSaleGoodsModels() != null) {
            for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size(); i++) {
                SaleGoodsModel saleGoodsModel = saleGoodsOrder.getSaleGoodsModels().get(i);
                saleGoodsOrder.getSaleGoodsModels().get(i).setSaleGoodsId(saleGoodsOrder.getSaleGoodsId());
                saleGoodsModel.setNumMatch("是");
                saleGoodsModel.setPackMatch("是");
                saleGoodsModel.setDataMatch("是");
                saleGoodsModel.setDataRemark("是");
                saleGoodsModel.setShippingMatch("是");
                saleGoodsMapper.insertSaleGoodsModelsPda(saleGoodsOrder.getSaleGoodsModels().get(i));

                //查询 销售订单子表id
                if (saleGoodsModel.getSaleorderModelId() != null) {
                    SaleorderModel saleorderModel = saleorderService.selectSaleorderModelByModelId(saleGoodsModel.getSaleorderModelId());
                    saleorderModel.setExecuteNum(saleorderModel.getExecuteNum() + saleGoodsModel.getNum());
                    saleorderModel.setRemainingNum(saleorderModel.getRemainingNum() - saleGoodsModel.getNum());
                    //      iSaleorderService.updateSaleorderModel(saleorderModel);
                }
            }
        }
        //添加审核订单
        Audit audit = new Audit();
        //销货单Id
        audit.setOrderId(saleGoodsOrder.getSaleGoodsId());
        //登陆人的companyid
        audit.setCompanyId(sysUser.getCompanyId());
        //主表的含税金额
        audit.setTaxAmount(saleGoodsOrder.getSaleGoodsTaxamount());
        //业务员id
        audit.setUserId(saleGoodsOrder.getSaleorderUserId());
        //客户id
        audit.setSupplierId(saleGoodsOrder.getCustomerId());
        //订单编号
        audit.setOrderNum(saleGoodsOrder.getSaleGoodsNum());
        //3为销货单
        audit.setOrderType("3");
        //状态0为 未审核
        audit.setAuditStatus("0");
        int insertAudit = auditService.insertAudit(audit);

        //将销售订单 的is_create_goods是否已生成销售订单 0改为1
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setSaleorderNum(saleGoodsOrder.getSaleGoodsNum());
        saleorderOrder.setDeptId(sysUser.getCompanyId());

        int updatenum = saleorderService.updateSaleorderIsCreateGoods(saleorderOrder);
//        return AjaxResult.error("这是错误测试");
        if (insertOrderNum >= 1 && insertAudit >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    public String getStr() {
        int len = 16;
        Random r = new Random();
        StringBuilder rs = new StringBuilder();
        for (int i = 0; i < len; i++) {
            rs.append(r.nextInt(10));
        }
        String a = rs.toString();
        // System.out.print(str);
        return a;
    }

    /**
     * 查看销售订单
     */
    @PostMapping("/look")
    @ResponseBody
    public AjaxResult edit(Long saleGoodsId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleGoodsId", saleGoodsId);
        hashMap.put("deptId", SecurityUtils.getLoginUser().getCompanyId());
//        hashMap.put("deptId", 101L);

        SaleGoodsOrder saleGoodsOrder = saleGoodsService.selectSaleGoodsById(hashMap);
        Map<String, Object> map = new HashMap<>();
        //判断子集是否存在
        if (saleGoodsOrder.getSaleGoodsModels().get(0).getSaleGoodsModelId() == null) {
            //没有的话 给个空的集合
            List<SaleGoodsModel> list = new ArrayList();
            saleGoodsOrder.setSaleGoodsModels(list);
            map.put("saleGoodsOrder", saleGoodsOrder);
        } else {
            for (Product product : saleGoodsOrder.getProducts()) {
                for (SaleGoodsModel saleGoodsModel : product.getSaleGoodsModel()) {
                    if (saleGoodsModel.getAllNum() != 0) {
                        if (saleGoodsModel.getUnit().equals("盒")) {
                            if (saleGoodsModel.getFactor() != 0) {
                                Long b = saleGoodsModel.getAmount() / saleGoodsModel.getFactor();
                                saleGoodsModel.setWarehousingNum(b);
                            }
                        } else {
                            saleGoodsModel.setWarehousingNum((long) saleGoodsModel.getAmount());
                        }
                    }
                }

            }
            map.put("saleGoodsOrder", saleGoodsOrder);
        }
        return AjaxResult.success("", map);
    }

    /**
     * 获取客户对象
     */
    @PostMapping("/selectCustObj")
    @ResponseBody
    public AjaxResult lists() {
        Map<String, Object> map = new HashMap<>();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//        Long companyId = 101L;
        SaleorderOrder saleorderOrder = new SaleorderOrder();
        saleorderOrder.setDeptId(companyId);
//        if (!WXShiroUtils.getSysUser().getDeptId().equals(WXShiroUtils.getSysUser().getCompanyId())) {
//            saleorderOrder.setUserId(WXShiroUtils.getUserId());
//        }
        List<SaleorderOrder> list = iSaleorderService.selectSaleorderCustObj(saleorderOrder);
        return AjaxResult.success(list);
    }

    /**
     * 查询销售订单详情
     */
    @PostMapping("/selectSaleorderList")
    @ResponseBody
    public AjaxResult selectSaleorders(SaleorderOrder saleorderOrder) {
        Map<String, Object> map = new HashMap<>();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
//        Long companyId = 101L;
        saleorderOrder.setDeptId(companyId);
        saleorderOrder.setIsCreateGoods("1");

        List<SaleorderOrder> saleorderOrderList = new ArrayList<SaleorderOrder>();
        List<SaleorderModel> saleorderModelList = new ArrayList<SaleorderModel>();

        if (saleorderOrder.getCompanyId() == null) {
            map.put("saleorderOrderList", saleorderOrderList);
            map.put("saleorderModelList", saleorderModelList);
            return AjaxResult.success(map);
        }
        saleorderOrder.setDeptId(companyId);
        saleorderOrderList = iSaleorderService.selectOrder(saleorderOrder);


        for (int i = 0; i < saleorderOrderList.size(); i++) {
            SaleorderOrder saleorderOrder1 = saleorderOrderList.get(i);
            saleorderModelList.addAll(saleorderOrder1.getSaleorderModels());


        }

        for (SaleorderModel saleorderModel : saleorderModelList) {
            if (saleorderModel.getAllNum() != 0) {
                if (saleorderModel.getUnit().equals("盒") || saleorderModel.getUnit() == "盒") {
                    List<Integer> list1 = procurementServer.selectProductType(saleorderModel.getProductType());
                    int a = list1.get(0);
                    if (a != 0) {
                        int b = saleorderModel.getRemainingNum() / a;
                        int c = saleorderModel.getExecuteNum() / a;
                        saleorderModel.setRemainingNum(b);
                        saleorderModel.setExecuteNum(c);
                    }

                }
            }

        }

        map.put("saleorderOrderList", saleorderOrderList);
        map.put("saleorderModelList", saleorderModelList);
        return AjaxResult.success(map);
    }

}
